package io.renren.modules.udp.utils;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.net.InetSocketAddress;

public class UdpClient {

	public static void run(int port, String context) throws Exception {

		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
					.handler(new UdpClientHandler());
			Channel ch = b.bind(5565).sync().channel();

			ByteBuf bufff = Unpooled.buffer();// netty需要用ByteBuf传输
			bufff.writeBytes(UdpStringUtils.hexStr2Bytes(context));// 对接需要16进制

			ch.writeAndFlush(new DatagramPacket(bufff, new InetSocketAddress("maxchinawuxi.vicp.cc", port)));
			// ch.writeAndFlush(new
			// DatagramPacket(Unpooled.copiedBuffer(context, CharsetUtil.UTF_8),
			// new InetSocketAddress("127.0.0.1", 5544)));

			if (!ch.closeFuture().await(5000)) {
				System.out.println("查询超时");
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		int port = 905;
		String context = "";

//		String user = "fjljkm";
//		String pswd = "fjljkm";
//		String msgtype = "01";
//		String filelength = "01 30";
//		String accesspswd = "00000000";
//		String equipid = "05518112902";

//		String user = "max";
//		String pswd = "max";
//		String msgtype = "02";
//		String filelength = "02 40";
//		String accesspswd = "00000000";
//		String equipid = "00000000";

//		String user = "fjljkm";
//		String pswd = "fjljkm";
//		String msgtype = "03";
//		String filelength = "01 30";
//		String accesspswd = "00000000";
//		String equipid = "05518112902";

		String user = "fjljkm";
		String pswd = "fjljkm";
		String msgtype = "04";

		String filelength = "01 30";
		String accesspswd = "00000000";
		String equipid = "05518112901";

		context = getContext(user,pswd,msgtype,filelength,equipid,accesspswd).trim();
		System.out.println("request msg:" + context);
		new UdpClient().run(port, context);
	}



	public static String getContext(String user,String pswd,String type,String filelength,String equip,String accesspswd) {
		String sGetContext = "";

		String  hexheader="";
		String  hexuser="";
		String hexpath="";
		String hexequip="";
		switch (type) {
		case "01":


			hexuser = UdpStringUtils.str2ASCII(11, user);
			String hexpswd = UdpStringUtils.str2ASCII(8, pswd);
			hexpath = UdpStringUtils.str2ASCII(0,UdpConstant.MSG_HEADER_FILEPATH.replace("$", user));
			hexheader = UdpConstant.MSG_HEADER_GETFILELENGTH;

			sGetContext = hexheader + " " +hexuser + hexpswd+hexpath;

			break;
		case "02":
			hexuser = UdpStringUtils.str2ASCII(11, user);
			hexheader = UdpConstant.MSG_HEADER_GETFILE;
			String hexfilecnt = Integer.toHexString((UdpConstant.MSG_HEADER_FILEPATH.replace("$", user)).length());
			hexpath = UdpStringUtils.str2ASCII(0,UdpConstant.MSG_HEADER_FILEPATH.replace("$", user));
			sGetContext = hexheader
					+ " " +hexuser
					+ ""+hexfilecnt
					+" "+hexpath
					+" "+"00 00 00 00"
					+" "+ filelength;
			break;
		case "03":
			hexequip = UdpStringUtils.str2ASCII(11, equip);
			hexheader = UdpConstant.MSG_HEADER_ACCESSEQUIP;

			String hexaccesspswd = UdpStringUtils.str2ASCII(0, accesspswd);
			String hextranstotal = "00 0B";

			String hexequipdata = UdpConstant.MSG_HEADER_TRANS
					+ " 08" //1字节，转发包的字节总数-3
					+ " 01"//1字节，访问方的ID。无要求时，可设定为01。
					+ " FF"//1字节，被访问的控制器的ID（范围2-255）255为广播地址
					+ " 01"//1字节，命令，读取控制器数据的命令为01。
					+ " 00 08"//2字节，控制器读写数据的初始地址。
					+ " 56"//1字节，控制器读写数据的数据范围。
					+ " 01 67"//2字节，校验位。** ## && CC ++ ++ %% DD DD DD … 的字节数据的累加和（高位在前，低位在后）。
					;


			sGetContext = hexheader
					+" " +hexequip
					+ ""+hexaccesspswd
					+ ""+hextranstotal
					+ " "+hexequipdata
					;
			break;
		case "04":
			hexequip = UdpStringUtils.str2ASCII(11, equip);
			hexheader = UdpConstant.MSG_HEADER_GETEQUIPSTATUS;
			sGetContext = hexheader
					+ " " +hexequip
					;
			break;

		default:
			break;
		}

		return sGetContext;
	}

}
